package com.ljm.filter;


import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljm.pojo.SecurityUser;
import com.ljm.pojo.User;
import com.ljm.security.TokenManager;
import com.ljm.utils.JwtUtils;
import com.ljm.utils.R;
import com.ljm.utils.ResponseUtil;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {


    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        // s设置 需要身份验证请求匹配器
        System.out.println("-----------------3333----------------");
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/userEntity/login","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
            System.out.println("-----------------111----------------");
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录成功
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @SneakyThrows
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        System.out.println("-----------------2222----------------");
       System.out.println("成功  ==  "+auth);
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        System.out.println("成功  ==  "+user);
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        ///  把token 保存在redis  中
       // redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
        System.out.println("成功  ==  "+token);
       // System.out.println(" ResponseUtil.out 01 ==  "+res.getWriter());
        res.setHeader("Authorization",token);
       // res.setHeader("username",user.getCurrentUserInfo().getUsername());
        //Cookie cookie = new Cookie("cookiename",token);
       redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(),user.getPermissionValueList());
        //res.addCookie(cookie);
//        res.setContentType("application/json;charset=UTF-8");
//        //ServletOutputStream outputStream = res.getOutputStream();
//        // 生成jwt返回
//        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
//        // String jwt = jwtUtils.generateToken(authentication.getName());

//        // Result result = Result.succ("");
//          //outputStream.write(JSONUtil.toJsonStr(R.ok()).getBytes("UTF-8"));
////          outputStream.flush();
////          outputStream.close();
//        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getCurrentUserInfo().getUsername(),token,user.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(authentication);
    //    chain.doFilter(req, res);
       ResponseUtil.out(res, R.ok().data("token",token));


//        res.setContentTy0pe("application/json;charset=UTF-8");
//        ServletOutputStream outputStream = res.getOutputStream();
//
//        // 生成jwt，并放置到请求头中
//        //String jwt = JwtUtils.generateToken(authentication.getName());
//        res.setHeader("Authorization", token);
//

//
//        outputStream.write(JSONUtil.toJsonStr(R.ok()).getBytes("UTF-8"));
//
//        outputStream.flush();
//        outputStream.close();
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @SneakyThrows
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {

        System.out.println("失败  ==  "+e);
        ResponseUtil.out(response, R.error());
    }
}
